/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets.map;

import database.Database;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Not Stephen
 */
public class GetDayPlannerServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private String makeDouble(int x) {
        String s = "";
        if (x < 10) {
            s = "0";
        }
        return s + x;
    }

    private String createCHTML() {
        String html = "";
        for (int h = 0; h < 23; h++) {
            int m = 0;
            while (m < 60) {
                html += " " + "|";
                m += 30;
                html += " " + "|";
                m += 30;

            }
        }
        html += " " + "|" + " ";
        return html;
    }
    
    private String createDPHTML() {
        String html = "";
        html += "<div class='miniDPDiv'></div><div id='mainDPDiv'>";
        String span1 = "<span class='hour1'";
        String span2 = "<span class='hour2'";
        String cSpan = "</span>";
        String str = "";
        int x = 0;
        for (int h = 0; h < 24; h++) {
            int m = 0;
            while (m < 60) {
                str = h + ":" + m;
                //0
                html += span1 + " id='" + h + ":" + m + "'  >" + makeDouble(h) + ":" + makeDouble(m) + "<input class='contentButton' type='button' value='Show' id='button_1_" + h + "' onclick='showContent1(" + h + ")' />" + cSpan + "<span class='content' id='content_1_" + h + "' ><textarea placeholder='Type a brief description of this times events' rows='5' maxlength='255' class='textareaDP' id='txtDP_" + (x++) + "' value=''/></span>";
                m += 30;
                //15
                str = h + ":" + m;
                html += span2 + " id='" + h + ":" + m + "' >" + makeDouble(h) + ":" + makeDouble(m) + "<input class='contentButton' type='button' value='Show'  id='button_2_" + h + "' onclick='showContent2(" + h + ")' />" + cSpan + "<span class='content' id='content_2_" + h + "' ><textarea placeholder='Type a brief description of this times events' rows='5' maxlength='255' class='textareaDP' id='txtDP_" + (x++) + "' value=''/></span>";
                m += 30;
            }
        }
        html += "</div>";
        return html;
    }

    private String createSOHTML() {
        String html = "";
        html += "<div class='stopoverDiv'><label>Name of the Place You're Staying: </label><input class='stopover_Name'/><br/><label>Time to be there</label><input class='stopover_time'/></div>";
        return html;
    }

    private ArrayList<String> parseStringIntoList(String htmlList, char del) {
        ArrayList<String> ls = new ArrayList<String>();
        int i = 0;
        while (htmlList.indexOf(del) != -1) {
            ls.add(htmlList.substring(0, htmlList.indexOf(del)));
            htmlList = htmlList.substring(htmlList.indexOf(del) + 1);
        }
        ls.add(htmlList);
        return ls;
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int tripId = Integer.parseInt(request.getParameter("tripId"));
        ArrayList<String> dates = parseStringIntoList(request.getParameter("dates"), ',');

        Connection c = null;
        c = Database.getConnection();
        String html = "";
        String cHtml = createCHTML();
        // String cHtml = createDPHTML();
        // String sHtml = createSOHTML();
        String finalHtml = "";
        if (c != null) {
            for (int i = 0; i < dates.size(); i++) {
                String date = dates.get(i);
                try {
                    PreparedStatement s = c.prepareStatement("SELECT * FROM dayplanner WHERE tripId = ? AND date = ?");
                    s.setInt(1, tripId);
                    s.setString(2, date);
                    ResultSet rs = s.executeQuery();
                    if (rs.next()) {
                        html = rs.getString("html");
                    } else {
                        html = cHtml;
                        PreparedStatement ss = c.prepareStatement("INSERT INTO dayplanner(tripId,date,html) VALUES(?,?,?)");
                        ss.setInt(1, tripId);
                        ss.setString(2, date);
                        ss.setString(3, html);
                        try {
                            ss.executeUpdate();
                        } catch (SQLException ex) {
                            Logger.getLogger(GetDayPlannerServlet.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                } catch (SQLException ex) {
                    // Logger.getLogger(GetDayPlannerServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
                if (i != dates.size() - 1) {
                    finalHtml += html + "|";
                } else {
                    finalHtml += html;
                }
            }
        }
        try {
            /* TODO output your page here. You may use following sample code. */

            out.println(finalHtml);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
